import os
import sys
import datetime

import pandas as pd

sys.path.append('..')

from tools.setting import DATA_DIR
from API.coinmarketcap import (get_all_coins_info,
                               get_all_tags_info)
from tools.logger import logger
COININFO_DATA_DIR = os.path.join(DATA_DIR, 'coins_information')
os.makedirs(COININFO_DATA_DIR, exist_ok=True)


def update_all_coins_and_tags_information():
    #获取币的基本信息和板块成分信息
    logger.info('开始获取币的基本信息')
    coins_info = get_all_coins_info()
    tags_info = get_all_tags_info()
    df = coins_info.merge(tags_info[['id', 'tags']], how='left', on=['id'])
    tags_list = []
    for tag in df['tags'].dropna():
        if tag:
            tags_list.extend(tag)
    tags = pd.Series(list(set(tags_list)))
    logger.info('分解板块成分')
    component_series = pd.Series(index=tags, dtype=object)
    df['tags_str'] = df['tags'].astype(str)
    for tag in tags:
        tag_coins = list(df[df['tags_str'].str.contains(tag).fillna(False)]['slug'])
        component_series[tag] = tag_coins
    logger.info('筛选稳定币列表')
    df_stablecoins = df[df['slug'].isin(component_series['stablecoin'])]
    logger.info('保存数据结果')
    df.to_csv(os.path.join(COININFO_DATA_DIR, 'coins_information.csv'), index=False)
    df_stablecoins.to_csv(os.path.join(COININFO_DATA_DIR, 'stablecoins_information.csv'), index=False)
    tags.to_csv(os.path.join(COININFO_DATA_DIR, 'tags_list.csv'), index=False)
    component_series.to_csv(os.path.join(COININFO_DATA_DIR, 'tag_component_latest.csv'), index=False)
    date = datetime.datetime.now().strftime('%Y-%m-%d')
    component_series.to_csv(os.path.join(COININFO_DATA_DIR, f'tag_component_{date}.csv'), index=False)


if __name__ == '__main__':
    update_all_coins_and_tags_information()
